package cn.HL.org.service.impl;

import cn.HL.basic.service.impl.BaseServiceImpl;
import cn.HL.basic.util.PageList;
import cn.HL.org.domain.Department;
import cn.HL.org.mapper.DepartmentMapper;
import cn.HL.org.query.DepartmentQuery;
import cn.HL.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service

public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath="";
        if(department.getParent()==null){
            dirPath="/"+department.getId();
        }else{
            Department department1 = departmentMapper.loadById(department.getParent().getId());
            dirPath=department1.getDirPath()  + "/"+department.getId();

        }
            department.setDirPath(dirPath);
        departmentMapper.update(department);
    }



    @Override
    public List<Department> findparent() {
        List<Department> departments = departmentMapper.loadAll();
        Map<Long,Department> allDepts= new HashMap<>();
        List<Department> firstDepts= new ArrayList<>();
        for (Department department : departments) {
            allDepts.put(department.getId(),department);
        }
        for (Department tmp : departments) {
            if(tmp.getParent_id()==null){
                firstDepts.add(tmp);
            }else{
                Department parent = allDepts.get(tmp.getParent_id());
                if(parent!=null){
                    parent.getChildren().add(tmp);
                }

            }
        }
        return firstDepts;
    }
}
